package cn.bdqn.asecu.service;

import cn.bdqn.asecu.config.FileHelper;
import cn.bdqn.asecu.config.FileStorageProperties;
import cn.bdqn.pojo.Know;
import cn.bdqn.pojo.MyFile;
import cn.bdqn.pojo.User;
import cn.bdqn.repository.Asecu_MyFileRepository;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;

@Service
public class MyFileService {

    private final Path uploadPath;

    public MyFileService(FileStorageProperties fileStorageProperties) {
        this.uploadPath = Paths.get(FileHelper.getUploadPath(fileStorageProperties), new String[0]).toAbsolutePath()
                .normalize();
        try {
            Files.createDirectories(this.uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Resource
    Asecu_MyFileRepository asecu_MyFileRepository;

    public List<MyFile> getfile(int id) {
        List<MyFile> fileList = asecu_MyFileRepository.findByCreator(id);
        return fileList;
    }

    /**
     *  上传文件
     * @param file
     * @param information
     * @param user
     * @return
     */
    public MyFile myfileUpload(MultipartFile file, String information, User user) {

        //文件原名称
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        String s = fileName.substring(0, fileName.lastIndexOf("."));
        System.out.println(s);
        MyFile myFile = null;
        try {
            if (fileName.contains("..")) {
                throw new IOException();
            }
            //文件格式
            String fileExtensionName = FileHelper.getExtFromFileName(fileName);
            System.out.println(fileExtensionName);
            //新文件名称
            String randomFileName = FileHelper.createRandomFileName(fileExtensionName);
            System.out.println("新："+randomFileName);
            Path targetLocation = Paths.get(this.uploadPath + File.separator + randomFileName, new String[0]);
            System.out.println(targetLocation);
            //储存到本地
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            myFile = new MyFile(randomFileName,fileExtensionName,new Date(),information,'是',uploadPath.toString(),fileExtensionName,user.getId(),file.getSize(),fileName);

            this.asecu_MyFileRepository.save(myFile);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return myFile;
    }


    /**
     * 根据id获取文件信息
     * @param id
     * @return
     */
    public MyFile getFileInfoById(Long id) {
        MyFile myFile = this.asecu_MyFileRepository.findById(id.intValue()).get();
        return myFile;
    }

    /**
     * 根据id加载文件资源
     * @param id
     * @return
     */
    public org.springframework.core.io.Resource loadFileAsResource(Long id) {
        try {
            MyFile myFile = getFileInfoById(id);
            Path filePath = Paths.get(myFile.getFilePath() + File.separator + myFile.getFileName(), new String[0])
                    .normalize();
            org.springframework.core.io.Resource resource = (org.springframework.core.io.Resource) new UrlResource(filePath.toUri());
            if (resource.exists()) {
                return resource;
            }
        } catch (NoSuchElementException | MalformedURLException ex3) {
        }
        return null;
    }

    /**
     * 删除文件
     * @param ids
     * @return
     */
    @Transactional
    public Boolean removeFile(Integer[] ids) {

        for (Integer id : ids) {
            org.springframework.core.io.Resource resource  = this.loadFileAsResource(id.longValue());
            try {
                this.asecu_MyFileRepository.deleteById(id);
                resource.getFile().delete();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }
}
